package com.online.onlinestudent.controller;

import com.online.onlinestudent.dto.AjaxResult;
import com.online.onlinestudent.entity.User;
import com.online.onlinestudent.service.ILoginService;
import com.online.onlinestudent.util.IdentityType;
import com.online.onlinestudent.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin // 允许前端访问
@Slf4j
@RestController
@RequestMapping("/login")
public class LoginAndRegisterController {

    @Autowired
    private ILoginService loginService;
    @Autowired
    private JwtUtil jwtUtil;
    @PostMapping
    public AjaxResult login(@RequestBody User user) {
        User login = loginService.doLogin(user);
        if (login != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("user_id", login.getId());
            map.put("username", login.getUsername());
            switch (login.getIsWho()) {
                case 0:
                    map.put("identity", IdentityType.STUDENT);
                    break;
                case 1:
                    map.put("identity", IdentityType.TEACHER);
                    break;
                case 2:
                    map.put("identity", IdentityType.ADMIN);
                    break;
                default:
                    // 处理未知的identity类型
                    throw new IllegalArgumentException("Unknown identity type: " + login.getIsWho());
            }
            String token = jwtUtil.generateToken(map);
            AjaxResult result = AjaxResult.success(map);
            result.put("token", token);
            return result;
        }
        return AjaxResult.fail();
    }

    @PostMapping("/register")
    public AjaxResult register(@RequestBody User user) {
        String flag = loginService.doRegister(user);
        if (flag.endsWith("成功")) {
            return AjaxResult.success("注册成功:"+flag);
        }
        return AjaxResult.fail("注册失败:"+flag);
    }
}
